package demo1;

import java.util.HashMap;
import java.util.Objects;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2021-11-02
 * Time:11:57
 */

class Person{
    public String id;
    public Person(String id){
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(id, person.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }//自定义类型要往哈希表放就要从写hashcode方法
}

class HashBuck<K,V>{
    static  class  Node<K,V>{
        public K key;
        public V val;
        public Node<K,V> next;
        public Node(K key,V val){
            this.key = key;
            this.val = val;
        }
    }

    public Node<K,V>[] array = (Node<K, V>[]) new Node[8];
    public int usedSize;

    public void put(K key,V val){
        Node<K,V> newNode = new Node<>(key,val);
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K,V> cur = array[index];
        while (cur != null){
            if (cur.key.equals(key)){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        cur = array[index];
        if (cur == null){
            array[index] = newNode;
        }else {
            while (cur.next !=null){
                cur = cur.next;
            }
            cur.next = newNode;
        }
        this.usedSize ++;
    }

    public V get(K key){
        int hash = key.hashCode();
        int index = hash % array.length;

        Node<K,V> cur = array[index];
        while (cur !=null){
            if (cur.key.equals(key)){
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
public class TestDemo {
    public static void main3(String[] args) {

    }
    public static void main(String[] args) {
        Person person1 = new Person("123");
        Person person2 = new Person("123");
        HashMap<Person,String> map = new HashMap<>();
//        HashBack<Person,String> map = new HashBack<>();
        //默认的容量是16  最大是2^30 默认的负载因子 0.75
        /*
        HashMap<>(); 默认值不是16 而是0 第一次PUT的时候容量才是16
        只有当数组的长度是2的次幂的时候 key&(table.length - 1) 才与 KEY%(TABLE.length)相等
        HashMap<>(18);//容量是接近于二次幂的数

        数组长度大于64 当前链表的长度超过8 且当前桶的个数大于等于64的时候才会把超过8的链表变成红黑树   binCount 超过8才会变成红黑树  才会把这个链表变成红黑树
         扩容是二倍扩容

         */
        HashBuck<Person,String> map1 = new HashBuck<>();
        map.put(person1,"bit");
        map.put(person2,"gaobo");
        System.out.println(map.get(person1));
    }
    public static void main1(String[] args) {
        Person person1 = new Person("123");
        Person person2 = new Person("123");
        System.out.println(person1.hashCode());
        System.out.println(person2.hashCode());
    }


}
